package com.ssm.trace;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@Component
@Slf4j
public class TraceIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String traceId = request.getHeader(TraceIdConstant.TRACE_ID);

        // 如果TraceId为空，则赋值(可能多微服务调用，会从上游Http中获取)
        if(StringUtils.isBlank(traceId)) {
            // 生成TraceId
            traceId = TraceIdContext.generateTraceId();
        }
        // 将TraceId设置进MDC
        TraceIdContext.setTraceId(traceId);
        //继续执行其他请求
        filterChain.doFilter(servletRequest, servletResponse);
        //请求处理完成后清空当前线程的TraceId
        TraceIdContext.clearTraceId();
    }
}
